// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

//操作excel用的类库
const xlsx = require('node-xlsx');

// 云函数入口函数
exports.main = async (event, context) => {
  try {
    let gameTitle = event.gameTitle
    let data = event.signUpList

    //1,定义excel表格名
    let dataCVS = gameTitle + '报名表.xlsx'
    //2，定义存储数据的
    let alldata = [];
    //3. 表头属性
    let head = ['考号', '姓名', '性别', '学校', '电话', '邮箱', '城市', '证件类型', '证件号', '年级', '组别', '导师', '状态']; 
    alldata.push(head);

    for (let key in data) {
      let arr = [];
      arr.push(data[key].contestant_id)
      arr.push(data[key].user.name);
      arr.push(data[key].user.sex);
      arr.push(data[key].user.school);
      arr.push(data[key].user.phone);
      arr.push(data[key].user.email);
      arr.push(data[key].user.city);
      arr.push(data[key].user.cardType);
      arr.push(data[key].user.cardId);
      arr.push(data[key].grade);
      arr.push(data[key].group);
      arr.push(data[key].tutor);
      arr.push(data[key].state);
      alldata.push(arr)
    }
    //3，把数据保存到excel里
    var buffer = await xlsx.build([{
      name: "mySheetName",
      data: alldata
    }]);
    //4，把excel文件保存到云存储里
    return await cloud.uploadFile({
      cloudPath: dataCVS,
      fileContent: buffer, //excel二进制文件
    })

  } catch (e) {
    console.error(e)
    return e
  }
}